package com.loop.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author zhangxiaolu
 * @since 2023-09-23 22:47
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        // 接收到数据并处理
        int len = msg.getLen();
        byte[] content = msg.getContent();

        System.out.println("服务器接收到的消息, 长度：" + len + ";内容：" + new String(content, StandardCharsets.UTF_8));
        System.out.println("服务器接收到消息的数量  = " + (++this.count));

        // 回送数据给客户端，随机id
        String string = UUID.randomUUID().toString();
        int length = string.getBytes(StandardCharsets.UTF_8).length;
        // 构建协议包
        MessageProtocol msg2 = new MessageProtocol();
        msg2.setLen(length);
        msg2.setContent(string.getBytes(StandardCharsets.UTF_8));
        ctx.writeAndFlush(msg2);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
